<template>
  <div>
    <div id="wrapper" class="pb-150">
      <!--顶部fixed部分-->
      <div class="fixed-top fixed-box">
        <div class="top-header border-bottom">
          <div class="top-back">
            <a @click="goBack"></a>
          </div>
          <h2 class="f36">订单详情</h2>
          <div class="top-right"></div>
        </div>
      </div>
      <div class="mt-97">
        <div class="bg-m1 f32 color-fff order_top_tip clearfix" v-if="state === '待付款'">
          <span class="icon_wait icon_mon">未付款&nbsp;
            <a class="bg-fff color-m1" href="javascript:void(0)" @click="goPay">去支付</a>&nbsp; 剩余时间：{{restTime}}</span>
        </div>
        <div class="bg-m1 f32 color-fff order_top_tip" v-else-if="state === '已付款'">
          <span class="icon_mon">您已付款，请&nbsp;
            <a class="bg-fff color-m1" href="javascript:void(0)" @click="goToServe">联系客服</a>&nbsp; 交易</span>
        </div>
        <div class="bg-2a f32 color-fff order_top_tip" v-else-if="state === '交易成功'">
          <span class="icon_firm">交易成功</span>
        </div>
        <div class="bg-999 f32 color-fff order_top_tip" v-else-if="state === '交易取消'">
          <span class="icon_fail">交易取消</span>
        </div>
      </div>
      <div class="detail_container bg-fff clearfix border-bottom">
        <!-- <img class="game_logo fl" :src="detail.goodsImg"> -->
        <img class="game_logo fl" src="~images/default_img.jpg">
        <div>
          <p class="titl f30 color-000">{{detail.goodsName}}</p>
          <p class="f28 mt-20 color-000">￥{{detail.price}}</p>
        </div>
      </div>
      <div v-if="tradeDescription.length" @click="showTradeDescription=true" class="detail_explain px-30 bg-fff border-bottom">
        <span class="exp-titl fl f28 color-000">交易说明</span>
        <i class="ico fr"></i>
      </div>
      <div class="detail_container bg-fff mt-20 border-bottom">
        <p class="f30 mb-30">
          <span class="color-666 pr-30">游戏区服</span>
          <span class="color-000">{{detail.platformName}} /{{detail.operatorName}}/ {{detail.areaName}}</span>
        </p>
        <p class="f30">
          <span class="color-666 pr-30">商品类型</span>
          <span class="color-000">游戏币</span>
        </p>
      </div>
      <div class="detail_container bg-fff border-bottom">
        <p class="f30 mb-30">
          <span class="color-666 pr-30">商品价格</span>
          <span class="color-666 fr">￥{{(detail.price/detail.goodsCount).toFixed(2)}}</span>
        </p>
        <p class="f30">
          <span class="color-666 pr-30">商品件数</span>
          <span class="color-666 fr">x{{detail.goodsCount}}</span>
        </p>
      </div>
      <div class="total_container bg-fff border-bottom">
        <p class="f30 mb-30">
          <span class="color-m1 fr ml-30">￥{{detail.price}}</span>
          <span class="color-666 fr">合计金额</span>
        </p>
      </div>
      <div class="detail_container bg-fff  mt-20">
        <p class="f30 mb-30">
          <span class="color-666 pr-30">订单编号</span>
          <span class="color-666">{{detail.orderId}}</span>
          <a class="copy ml-20 color-666 f24" :data-clipboard-text="detail.orderId" @click="copy" ref="mgCoy">复制</a>
        </p>
        <p class="f30">
          <span class="color-666 pr-30">下单时间</span>
          <span class="color-666" v-if="detail.createTimeString" v-text="detail.createTimeString"></span>
        </p>
      </div>
      <div class="fixed-bottom mancon-btn pr-30 py-20 bg-fff border-top" v-if="state === '待付款'">
        <a class="f30 color-fff border border-color bg-m1 fr" @click="goPay">去付款</a>
        <!-- <a class="f30 color-666 border border-color666 cancel fr" @click="showMessageConfirm = true">取消订单</a> -->
      </div>
      <div class="fixed-bottom mancon-btn pr-30 py-20 bg-fff border-top" v-if="state === '已付款' || state === '交易成功'">
        <a class="f30 color-m1 border border-color cancel fr" href="javascript:void(0)" @click="goToServe">联系客服</a>
        <i class="titcur fr" @click="alertMessage"></i>
      </div>
      <div class="maskdiv" v-if="showTradeDescription" @click="showTradeDescription=false"></div>
      <!--交易说明-->
      <div class="sv-guarantee fixed-bottom border-top bg-fff  " v-if="showTradeDescription" style="z-index: 60;overflow: scroll" :style="{'max-height': .6 * height + 'px'}">
        <div class="scgtee-titl f32 color-666 border-bottom">
          <a class="close mr-30" @click="showTradeDescription=false"></a>交易说明
        </div>
        <div class="ift-list color-333 f28 px-30 py-20 mg_trade_description" v-html="tradeDescription">
        </div>
      </div>
      <div class="message_confirm" v-if="showMessageConfirm">
        <div class="maskdiv" style="z-index: 1" v-if="showMessageConfirm" @click="showMessageConfirm=false"></div>
        <!--取消订单-->
        <div class="dialog-box bg-fff" style="margin: auto; z-index: 2">
          <div class="dialog-main">
            <div class="dialog-body color-000" id="errortx">确定取消订单？</div>
            <div class="dialog-foot">
              <a class="dialog_close border-right color-m1" href="javascript:void(0);" @click="showMessageConfirm=false">我再想想</a>
              <a class="dialog_close color-000" href="javascript:void(0);" @click="cancelOrder">去意已决</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getMenu } from './buyerStoreMenuNew'
import Clipboard from 'clipboard'
import { BuyerCenterApi } from 'api/index'

export default {
  data() {
    return {
      showMessageConfirm: false,
      height: window.innerHeight,
      showTradeDescription: false, // 是否显示交易说明
      tradeDescription: '', // 交易说明内容
      params: this.$route.params,
      restTime: null, // 创建时间 + 30 * 60 * 1000 - 当前时间
      clipboard: null,
      state: '', // 订单的状态
      param: '1', // 返回订单列表的状态
      detail: {},
      jsPath: 'http://consignment.5173.com/ajax.axd?methodName=GetOrderIMInfo',
      dbPath: 'http://danbao.5173.com/ajax.axd?methodName=GetOrderIMInfo',
      zhPath: 'http://gameid.5173.com/BankInfo.axd?methodName=GetOrderIMInfo',
      syPath: 'http://sy.5173.com/api/order/getorderim',
      scPath: 'http://yxbmall.5173.com/gamegold-facade-frontend/services/orderdata/getOrderIm'
    }
  },
  created() {
    this.$indicator.open({
      spinnerType: 'fading-circle'
    })
  },
  destroy() {
    this.$indicator.close() // 关闭加载中提示
  },
  mounted() {
    this.init()
    this.clipboard = new Clipboard(this.$refs['mgCoy'])
    this.setXiaoNeng()
  },
  methods: {
    // 小能客服配置
    setXiaoNeng() {
      const s1 = document.createElement('script');
      s1.type = 'text/javascript';
      s1.text = 'NTKF_PARAM = {' +
        'siteid: "bq_1000",' +
        'settingid: "bq_1000_9999",' +
        'uid: "",' +
        'uname: "",' +
        'isvip: "0",' +
        'userlevel: "1",' +
        'erpparam: "abc"' +
        '}';
      document.body.appendChild(s1);
      const s = document.createElement('script');
      s.type = 'text/javascript';
      s.src = encodeURI('https://dl.ntalker.com/js/b2b/ntkfstat.js?siteid=bq_1000');
      s.charset = "utf-8";
      document.body.appendChild(s);
    },
    alertMessage() {
      const qq = this.detail.customServiceQQ || ''
      if (!!qq) {
        this.$messagebox({
          message: "如点击联系客服无法启动QQ，请加客服QQ号(" + qq + ")"
        })
      } else {
        this.$messagebox({
          message: "该订单正在分配客服"
        })
      }
    },
    goToServe() {
      // const qq = this.detail.serviceQQ || ''
      // if(/baidu/i.test(navigator.userAgent.toLowerCase())||/MicroMessenger/i.test(navigator.userAgent.toLowerCase())){
      //   this.$messagebox({
      //     message: "如点击联系客服无法启动QQ，请加客服QQ号("+ qq +")"
      //   })
      // }else {
      //   window.location.assign('mqqwpa://im/chat?chat_type=wpa&uin=' + qq + '&version=1&src_type=web&web_src=oicqzone.com')
      // }
      this.getPcService(this.detail.orderId, 3)
    },
    //主站商品联系客服（主站未开启环信暂用版本）
    getPcService(Id, ServiceType) {
      //账号5 寄售2 担保1
      let url = ''
      switch (parseInt(ServiceType)) {
        case 10:
          url = this.scPath
          break;
        case 6:
          url = this.scPath
          break;
        case 5:
          url = this.zhPath
          break;
        case 2:
          url = this.jsPath
          break;
        case 3:
          url = this.syPath
          break;
        case 1:
          url = this.dbPath
          break;
        default:
      }
      let urlpath = this.$concatUrl({ orderid: Id, usertype: 1, tradingtype: ServiceType, callback: 'callback' }, url)
      BuyerCenterApi.getOrderIm(urlpath).then(res => {
        if (res.data) {
          if (res.data.Order) {
            this.goCustomer(res.data.Order, urlpath)
          } else {
            //							this.$toast({ message: '联系客服失败，请稍后重试' })
            NTKF.im_openInPageChat('bq_1000_1472795888825');
          }
        }
      })
    },
    goCustomer(val, url) {
      if (Object.keys(val).length) {
        if (val.DefaultIM == 1 || (val.DefaultIM == 2 && val.WYCustomService) || (val.DefaultIM == 2 && !val.WYCustomService && val.IsOpenHX) || (!val.DefaultIM && val.IsOpenHX)) {
          location.href = `/member/huanxin1.html?url=${encodeURIComponent(url)}`
        } else {
          if (/baidu/i.test(navigator.userAgent.toLowerCase()) || /MicroMessenger/i.test(navigator.userAgent.toLowerCase())) {
            this.$messagebox({
              message: "如点击联系客服无法启动QQ，请加客服QQ号(" + val.CustomServiceQQ + ")"
            })
          } else {
            window.location.assign('mqqwpa://im/chat?chat_type=wpa&uin=' + val.CustomServiceQQ + '&version=1&src_type=web&web_src=oicqzone.com')
          }
        }
      }
    },
    /* 返回到列表页 */
    goBack() {
      var param = this.param
      if (param == '4') {
        param = '-1'
      } else if (param == '2') {
        param = '1|2'
      } else if (param == '1') {
        param = '0'
      }
      this.$router.push({
        path: '/vue/buyerCenter/buyOrderList/' + param
      })
    },
    copy() {
      this.clipboard.on('success', e => {
        this.$toast('订单号已复制到剪贴板')
        e.clearSelection();
      });
      this.clipboard.on('error', e => {
        this.$toast('复制失败，请尝试长按复制')
      });
    },
    /* 去支付 */
    goPay() {
      this.$indicator.open()
      let orderId = this.params.orderId
      this.$http.post(this.$CONSTANTS.APIMGCoin + "pay/orderPay", { orderId, sourceChannel: 2 }).then(({ data }) => {
        location.href = 'https://mypay.5173.com/PaymentWap/PayExternalV2.aspx?' + data.data.payUrl
      }).then(() => {
        this.$indicator.close()
      })
    },
    /* 取消订单 */
    cancelOrder() {
      this.showMessageConfirm = false
      this.$indicator.open()
      this.$http.post('/api/mobile-order-service/rs/buyer/order/cancel', { orderId: this.params.orderId }).then(({ data: res }) => {
        if (res.success) {
          this.setDetail()
        } else {
          this.$toast(res.responseStatus.message)
        }
      }).then(() => {
        this.$indicator.close()
      })
    },
    init() {
      /* 获取订单详情 */
      this.setDetail().then(() => {
        /* 获取描述 */
        // let params = {gameId: this.detail.gameId, goodsType: this.detail.goodsType}
        // this.$http.get(this.$CONSTANTS.APICategory + 'goodsTypeGameService/selectTradeDescription', {params}).then(res => {
        //   this.tradeDescription = res.data.tradeDescription || ''
        // }).then(() => {
        //   this.$indicator.close()
        // })
        this.$indicator.close()
      })
    },
    /* 配置详情 */
    setDetail() {
      return this.$http.post(this.$CONSTANTS.APIMGCoin + 'buyer/getOrderDetail', {
        orderId: this.params.orderId
      }).then(({ data }) => {
        if (data.success) {
          data.data.createTime = new Date(data.data.createdDate) // 创建时间
          data.data.currentTime = new Date(data.data.currentTime) // 当前时间
          data.data.createTimeString = this._turnTime(data.data.createTime) // 格式化创建时间
          this.detail = data.data
          this.state = getMenu(this.detail.orderStatus).name // 获取该订单的状态名称
          this.param = getMenu(this.detail.orderStatus).param
          console.log(this.state)
          if (this.state === '待付款')
            this.showRestTime(this.detail.createTime, this.detail.currentTime)
        } else {
          this.$toast(data.responseStatus.message)
        }
      })
      return this.$http.get(`/api/mobile-order-service/rs/buyer/order/${this.params.orderId}`).then(res => {
        if (!res.data.success) {
          alert(res.data.responseStatus.message)
          location.href = '/'
        } else {
          res.body.result.createTime = new Date(res.body.result.createTime) // 创建时间
          res.body.result.currentTime = new Date(res.body.currentTime) // 当前时间
          res.body.result.createTimeString = this._turnTime(res.body.result.createTime) // 格式化创建时间
          this.detail = res.body.result // 配置详情信息
          this.state = getMenu(this.detail.orderStatus).name // 获取该订单的状态名称
          this.param = getMenu(this.detail.orderStatus).param
          if (this.state === '待付款')
            this.showRestTime(this.detail.createTime, this.detail.currentTime)
        }
      })
    },
    /* 计算剩余时间 */
    showRestTime(createDate, currentTime) {
      function _() {
        let rest = (createDate.getTime() + 30 * 60 * 1000 - currentTime.getTime()) / 1000
        if (rest <= 0) rest = 0
        this.restTime = this._turnNum(parseInt(rest / 60)) + '分' + this._turnNum(parseInt(rest % 60)) + '秒'
        currentTime = new Date(currentTime.getTime() + 1000)
      }
      _.apply(this)
      setInterval(() => {
        _.apply(this)
      }, 1000)
    },
    _turnNum(num) {
      if (num < 10) return '0' + num
      return num
    },
    _turnTime(date) {
      return date.getFullYear() + '-' +
        this._turnNum(date.getMonth() + 1) + '-' +
        this._turnNum(date.getDate()) + ' ' +
        this._turnNum(date.getHours()) + ':' +
        this._turnNum(date.getMinutes()) + ':' +
        this._turnNum(date.getSeconds())
    }
  }
}
</script>
<style src="css/member/member-order.css" scoped></style>
<style>
.mg_trade_description img {
  max-width: 100%;
}
</style>
<style scoped>
.message_confirm {
  position: fixed;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  top: 0;
  z-index: 1000;
}
</style>